package com.changpay.zywy.ui.fragment.main

import android.content.Context
import android.content.Intent
import android.support.v4.widget.SwipeRefreshLayout
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.example.havi.bean.HyChatUser
import com.example.havi.helper.ChatHelper
import com.example.havi.interfaces.LoginCallBack
import com.example.havi.ui.ChatActivity
import com.changpay.zywy.R
import com.changpay.zywy.app.App
import com.changpay.zywy.base.BaseMvpFragment
import com.changpay.zywy.bean.*
import com.changpay.zywy.constant.Constant
import com.changpay.zywy.ext.showToast
import com.changpay.zywy.ext.sss
import com.changpay.zywy.http.RetrofitHelper
import com.changpay.zywy.mvp.contract.HomeContract
import com.changpay.zywy.mvp.presenter.HomePresenter
import com.changpay.zywy.ui.activity.freeze.FreezeActivity
import com.changpay.zywy.ui.activity.loan.LoanFirstActivity
import com.changpay.zywy.ui.activity.machinecontrol.MachineControlActivity
import com.changpay.zywy.ui.activity.main.*
import com.changpay.zywy.ui.activity.mine.RenZhenActivity
import com.changpay.zywy.ui.activity.partent.QuDaoActivity
import com.changpay.zywy.ui.activity.power.PowerActivity
import com.changpay.zywy.ui.activity.serivce.SelectProjectActivity
import com.changpay.zywy.ui.activity.serivce.ServiceActivity
import com.changpay.zywy.ui.activity.serivce.SetLowerPriceActivity
import com.changpay.zywy.ui.banner.holder.MZViewHolder
import com.changpay.zywy.utils.ImageLoader
import com.changpay.zywy.utils.Preference
import com.changpay.zywy.utils.TimeUtils
import io.reactivex.Observable
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.home_gonggao_layout.*
import kotlinx.android.synthetic.main.home_tab_layout.*
import java.lang.StringBuilder

class HomeFragment : BaseMvpFragment<HomeContract.View, HomeContract.Presenter>(), HomeContract.View {


    /**
     * local password
     */
    private var approve: Int by Preference(Constant.IS_APPROVE, 0)

    private var bank: Int by Preference(Constant.IS_BANE, 0)

    private var chat_id: String by Preference(Constant.CHAT_ID, "")

    private var chat_passwrod: String by Preference(Constant.CHAT_PASSWORD, "")

    private var kefubean:KeFuInfo ?= null


    override fun showUnreadInfo(data: UnReadInfoBean) {
//        tv_shop_unread.text = data.merchant_count.toString()
//        tv_shop_unread.visibility = if (data.merchant_count == 0) View.INVISIBLE else View.VISIBLE

        tv_member_unread.text = data.partner_count.toString()
        tv_member_unread.visibility = if (data.partner_count == 0) View.INVISIBLE else View.VISIBLE

        tv_zhen_ce_unread.text = data.member_rate_count.toString()
        tv_zhen_ce_unread.visibility = if (data.member_rate_count == 0) View.INVISIBLE else View.VISIBLE
    }

    override fun showHello(data: UserInfo) {
        approve = data.is_approve
        bank = data.is_bank
        val chatUser = HyChatUser()

        chatUser.avatar = data.member_avatar
        chatUser.chatPassword = chat_passwrod
        chatUser.chatUserName = data.truename
        chatUser.nickName = data.truename
        chatUser.chatId = chat_id
        chatUser.userId = data.member_id.toString()
        ChatHelper.getInstance().syncChatUserInfo(chatUser)
        if (data.is_approve == 0) {
            home_tv_title.text = "请实名认证"
            home_tv_title.setOnClickListener { startActivity(RenZhenActivity::class.java) }
        } else {
            if (data.member_name.isEmpty()) {
                // 获取当时时间是中午下午,还是晚上
                val dateSx = TimeUtils.dateSx
                home_tv_title.text = dateSx + "," + data.truename
                home_tv_title.setOnClickListener { }
            } else {
                // 获取当时时间是中午下午,还是晚上
                val dateSx = TimeUtils.dateSx
                home_tv_title.text = dateSx + "," + data.member_name
                home_tv_title.setOnClickListener { }
            }
        }
    }

    companion object {
        fun getInstance(): HomeFragment = HomeFragment()
    }

    /**
     * is Refresh
     */
    private var isRefresh = true


    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        mPresenter?.getInCome(token, "2.0")
    }


    /**
     * banner datas
     */
    private lateinit var bannerDatas: ArrayList<Adv>


    /**
     * banner datas
     */
    var GongaoViews = mutableListOf<TextView>()


    override fun createPresenter(): HomeContract.Presenter = HomePresenter()

    override fun attachLayoutRes(): Int = R.layout.fragment_home

    override fun showGongGao(data: List<GongGaoBean>) {
        val gongGaoString = StringBuilder()
        if (data.isEmpty()) {
            gongGaoString.append("暂无公告")
        } else {
            for (index in 0 until data.size) {
                gongGaoString.append(data[index].title + "    ")
            }
        }
        tv_gong_gao.text = gongGaoString.toString()
    }


    override fun showInCome(data: TodayEarnings) {
        home_today_income.setContent(data.today_info.earnings_amount)
        if (data.today_info.earnings_amount.contains("-")) {
            minus.visibility = View.VISIBLE
        } else {
            minus.visibility = View.INVISIBLE
        }
        home_today_action.setContent(data.today_info.activation_count)
        home_today_trading.setContent(data.today_info.trading_amount)

    }


    override fun showBanner(data: Banner) {
        bannerDatas = data.adv_list as ArrayList<Adv>
        val bannerFeedList = ArrayList<String>()
        val bannerTitleList = ArrayList<String>()
        Observable.fromIterable(data.adv_list)
            .subscribe { list ->
                bannerFeedList.add(list.adv_code)
                bannerTitleList.add("")
            }

        home_banner.setPages(
            bannerFeedList
        ) { BannerViewHolder() }
        home_banner.start()
    }

    override fun lazyLoad() {
        swipeRefreshLayout.isRefreshing = true
        mPresenter?.getBanner()
        mPresenter?.getInCome(token, "2.0")
        mPresenter?.getUserInfo(token)
        mPresenter?.getSystemMsgList()
        mPresenter?.getUnreadInfo(token)

        val param = hashMapOf<String, String>()
        param["key"] = token
        RetrofitHelper.service.get_kfu_info(param).sss(this)
        {
            kefubean = it.result
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        mLayoutStatusView = multiple_status_view
        home_banner?.run {
            duration = 1500
        }
        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }

        tv_gong_gao.isSelected = true

        home_tab_one.setOnClickListener(onClickListener)
        home_tab_two.setOnClickListener(onClickListener)
        home_tab_three.setOnClickListener(onClickListener)
        home_tab_four.setOnClickListener(onClickListener)
        home_tab_five.setOnClickListener(onClickListener)
        home_tab_six.setOnClickListener(onClickListener)
        home_tab_eight.setOnClickListener(onClickListener)
        home_tab_seven.setOnClickListener(onClickListener)
        home_today_total_action.setOnClickListener(onClickListener)
        home_today_total_trad.setOnClickListener(onClickListener)
        home_today_total_income.setOnClickListener(onClickListener)
        ll_gong_gao.setOnClickListener(onClickListener)
        service.setOnClickListener(onClickListener)


    }


    private val onClickListener = View.OnClickListener { view ->

        if (approve == 0) {
            showToast("请先实名认证")
            startActivity(RenZhenActivity::class.java)
            return@OnClickListener
        }
        when (view.id) {
            R.id.home_tab_one -> startActivity(IncomeActivity::class.java)
            R.id.home_tab_two ->  {
                Intent(context, SelectProjectActivity::class.java).run {
                    type = "2"
                    putExtra("title", "设置下级政策")
                    startActivity(this)
                }
            }
            R.id.home_tab_three -> startActivity(LoanFirstActivity::class.java)
            R.id.home_tab_four -> startActivity(MachineControlActivity::class.java)
            R.id.home_tab_five ->startActivity(FreezeActivity::class.java)
            R.id.home_tab_six ->startActivity(PowerActivity::class.java)
            R.id.home_tab_seven -> startActivity(QuDaoActivity::class.java)
            R.id.home_tab_eight -> startActivity(ServiceActivity::class.java)
            R.id.home_today_total_action -> startActivity(TodayActionActivity::class.java)
            R.id.home_today_total_trad -> startActivity(TodayTradingActivity::class.java)
            R.id.home_today_total_income -> startActivity(IncomeActivity::class.java)
            R.id.ll_gong_gao -> startActivity(GongGaoActivity::class.java)
            R.id.service-> GotoService()
        }
    }


    override fun hideLoading() {
        swipeRefreshLayout?.isRefreshing = false
    }







    override fun onResume() {
        super.onResume()
        swipeRefreshLayout.isRefreshing = true
        mPresenter?.getInCome(token, "2.0")
        mPresenter?.getUserInfo(token)
        mPresenter?.getUnreadInfo(token)
        home_banner.start()
    }

    override fun onPause() {
        super.onPause()
        home_banner.pause()
    }

    class BannerViewHolder : MZViewHolder<String> {

        private var mImageView: ImageView? = null

        override fun createView(context: Context): View {
            // 返回页面布局
            val view = LayoutInflater.from(context).inflate(R.layout.banner_item, null)
            mImageView = view.findViewById(R.id.banner_image)
            return view
        }

        override fun onBind(context: Context, position: Int, data: String) {
            // 数据绑定
            ImageLoader.load(data, mImageView)
        }
    }


    private fun GotoService() {
        val login = ChatHelper.getInstance().isLogin
        if (login) {
            // 打开客服聊天
            if (kefubean!=null) {
                ChatActivity.startActivity(
                    context,
                    kefubean!!.member_id.toString(),
                    kefubean!!.member_name,
                    kefubean!!.member_avatar,
                    kefubean!!.chat_id,
                    kefubean!!.member_mobile
                )
            } else {
                showToast("暂无客服信息")
            }
        } else {
            showToast("聊天登录中")
            App.chatHelper?.login(chat_id, chat_passwrod, object :
                LoginCallBack {
                override fun onSuccess() {
                    //判断是否为客服
                    // 打开客服聊天
                    if (kefubean!=null)  {
                        ChatActivity.startActivity(
                        context,
                        kefubean!!.member_id.toString(),
                        kefubean!!.member_name,
                        kefubean!!.member_avatar,
                        kefubean!!.chat_id,
                        kefubean!!.member_mobile
                        )
                    } else {
                        showToast("暂无客服信息")
                    }
                }

                override fun onError(code: Int, message: String) {
                    showToast("聊天暂时登录失败")
                }
            })
        }
    }


}